package com.sto.stoapp.activity.scanner;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.scan.ScanRuleManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;

@SuppressLint({ "HandlerLeak", "NewApi" })
public class StoScanSendCarScanActivity extends StoListenerActivity {
	private StoHhmEditText carCode;
	private StoHhmEditText nextStation;
	// private StoHhmEditText code;
	private DataBusinessEntity dataBusiness;
	// private int MAX_CAR_ID_LEN = 6;
	private List<EditText> edit = new ArrayList<EditText>();
	private String nextStationCode = "", nextStationName = "";
	private final int DESTINATION_RESULT = 0xfd;
	private String busiType = HomeBroadAction.SCANNER_MAN_BROAD;
	// 手动结果
	protected static final int HAND_RESULT = 0x4f;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == HAND_RESULT) {
				if (CheckItemData(msg.obj.toString(), HAND_RESULT)) {
					processScanData();
				}
				code.setText("");
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_sendcar_scan);
		Bundle extras = getIntent().getExtras();
		busiType = extras.getString("busiType");
		this.setTitleBottom(R.string.send_car_piece_scan, busiType);
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_SEND_CAR);
		} else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_CENTER_SEND_CAR);
		}
		// 航空-扫描员-发车
		else if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_AVIATION_SEND_CAR);
		}
	}

	private void initWidget() {
		carCode = (StoHhmEditText) this.findViewById(R.id.send_car_id);
		nextStation = (StoHhmEditText) this.findViewById(R.id.next_station);

		code = (StoHhmEditText) this.findViewById(R.id.sanning_code);
		// ticketNumber = (TextView)
		// this.findViewById(R.id.nophone_tickets_text);
		// code.setInputType(InputType.TYPE_CLASS_TEXT);
		// code.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
		edit.add(carCode);
		edit.add(nextStation);
		edit.add(code);
		if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
			addUploadTable(EnumTableNames.STATUS_TABLE_SEND_CAR);
		} else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
			addUploadTable(EnumTableNames.STATUS_TABLE_CENTER_SEND_CAR);
		}
		// 航空-扫描员-发车
		else if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {

			addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_SEND_CAR);
		} else {

		}
	}

	/**
	 * 扫描数据处理
	 */
	@SuppressLint("NewApi")
	private void processScanData() {
		try {
			if (!code.getText().toString().isEmpty()) {
				if (addPieceRecord()) {
					this.addCodeNumber();
					setSaveData(true);
					// SoundManager.getInstance(this).playSuccessSound();
					Helper.showSoundAndVibrator(this, true);
					addScanRecordInfo(code.getText().toString());
					// ticketNumber.setText(String.valueOf(++count));
					code.setSelection(code.length());

				}
				// 提示插入数据失败
				else {
					Helper.showSoundToast(this,
							getString(R.string.code_repeat), false);
				}
				ScanOpen();
			} else if (code.getText().toString().isEmpty()) {
				// 提示单号不能为空

			}

		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	/**
	 * 数据保存
	 * 
	 * @return true/成功 or false/失败
	 */
	private boolean addPieceRecord() {
		boolean ret = false;

		// 单号
		dataBusiness.setBar_code_number(code.getText().toString());

		dataBusiness.setCodeType(getExpType(code.getText().toString()));
		// 下一站
		dataBusiness.setNext_station(nextStationCode);
		// 下一站名称
		dataBusiness.setUser_defined3(nextStation.getText().toString());
		// 车辆ID
		dataBusiness.setCarID_number(carCode.getText().toString());

		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());
		if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
			// 扫描类型
			dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_SEND_CAR
					.getOpCode());
			// 插入数据
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_SEND_CAR);
		} else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
			// 扫描类型
			dataBusiness
					.setCommand_type(EnumTableNames.STATUS_TABLE_CENTER_SEND_CAR
							.getOpCode());
			// 插入数据
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_CENTER_SEND_CAR);
		}
		// 航空-扫描员-发车
		else if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			// 扫描类型
			dataBusiness
					.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_SEND_CAR
							.getOpCode());
			// 插入数据
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_AVIATION_SEND_CAR);
		} else {

		}

		return ret;
	}

	/**
	 * 监听控件
	 */
	private void initListen() {

		carCode.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				nextStation.requestFocus();
				// nextStation.setSelection(nextStation.getText().toString()
				// .length());
			}

			@Override
			public void onEditClickListener(View v) {
				if (carCode.getText().toString().length() != CARID_LENGTH) {
					Helper.showSoundToast(StoScanSendCarScanActivity.this,
							"车辆id位数不对", false);
					carCode.setText("");
					return;
				}
				if (!carCode.getText().toString().matches("[0-9]+")) {
					Helper.showSoundToast(StoScanSendCarScanActivity.this,
							"车辆id非法", false);
					carCode.setText("");
				} else {
					code.requestFocus();
					code.setSelection(code.getText().toString().length());
				}
			}
		});
		/*
		 * carCode.setOnClickListener(new StoOnClickListener(this) {
		 * 
		 * @Override public void mHonClick(View v) {
		 * if(carCode.getText().toString().length() != MAX_CAR_ID_LEN){
		 * Helper.showSoundToast(StoScanSendCarScanActivity.this, "车辆id位数不对",
		 * false); return; }
		 * if(!carCode.getText().toString().matches("[0-9]+")){
		 * Helper.showSoundToast(StoScanSendCarScanActivity.this, "车辆id非法",
		 * false); }else{ code.requestFocus(); } } });
		 */

		nextStation.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
//				selectNextStation();
			}
		});

		findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				selectNextStation();
			}
		});

		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				carCode.requestFocus();
				// carCode.setSelection(carCode.getText().toString().length());
			}

			@Override
			public void onEditClickListener(View v) {
				codeProcess();
				/*
				 * Message msg = handler.obtainMessage(); msg.what =
				 * HAND_RESULT; msg.obj = code.getText().toString();
				 * handler.sendMessage(msg);
				 */
			}
		});
		/*
		 * code.setOnClickListener(new StoOnClickListener(this) {
		 * 
		 * @Override public void mHonClick(View v) { Message msg =
		 * handler.obtainMessage(); msg.what = HAND_RESULT; msg.obj =
		 * code.getText().toString(); handler.sendMessage(msg); } });
		 */
		/*
		 * code.setEditScanListener(new EditScanListener() {
		 * 
		 * @Override public void onScan() { ScanOpen(); }
		 * 
		 * @Override public void offScan() { ScanOff(); } });
		 */

		for (EditText editListener : edit) {

			/*
			 * 监听EditText内容个数
			 */
			editListener.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					if (nextStation.getText().toString().isEmpty()) {
						nextStationCode = "";
						nextStationName = "";
					}
					if (code.getText().toString().trim().length() == 9
							&& Helper.isNumeric(code.getText().toString()
									.trim())) {
						code.setText("STO" + code.getText().toString().trim());
						code.setSelection(12);
						// code.selectAll();
					} else if (code.getText().toString().trim().length() == 12) {

					} else if (code.getText().toString().trim().length() == 0) {

					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});
		}
	}

	/**
	 * 单号逻辑处理判断
	 * 
	 * @author wxf
	 * 
	 */
	private void codeProcess() {
		String codeName = code.getText().toString();

		GetTableParcel data;
		if (codeName.length() == 0) {
			Helper.showSoundToast(this, getString(R.string.code_empty), false);
		} else {
			if (codeName.length() == NEXT_STATION_LENGTH) {
				data = queryNextStation(codeName);
				if (data != null) {
					nextStation.setText(data.getSelectName());
					nextStationCode = data.getSelectCode();
					nextStationName = data.getSelectName();
				} else {
					nextStationName = "";
					Helper.showSoundToast(this, getString(R.string.undefined),
							false);
				}
				code.setText("");

			} else {
				Message msg = handler.obtainMessage();
				msg.what = HAND_RESULT;
				msg.obj = code.getText().toString();
				handler.sendMessage(msg);
			}
		}
	}

	/**
	 * 选择下一站
	 */
	private void selectNextStation() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (nextStation.getText().toString().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_NEXT_NETSITE_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_NEXT_NETSITE_ONLY_LIKE);
				tableParcel.setSelectField(new String[] { "%"
						+ nextStation.getText().toString() + "%" });
			}
			tableParcel.setSelectCode(SITE_CODE_NUMBER);
			tableParcel.setSelectName(SITE_CODE_NAME);
			tableParcel.setProperty(null);
			Intent intent = new Intent(this, StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, DESTINATION_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("selectNextStation", e.getMessage());
		}
	}

	/**
	 * 选择列表返回的结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == DESTINATION_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			if (courierEntity != null) {
				nextStation.setText(courierEntity.getSelectName());
				nextStation.setSelection(nextStation.length());
				nextStationCode = courierEntity.getSelectCode();
				System.out.println(nextStationCode + ":"
						+ courierEntity.getSelectName());
				if (nextStationCode.length() > 0) {
					nextStationName = courierEntity.getSelectName();
					carCode.requestFocus();
				}
			}
		} else if (requestCode == DESTINATION_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			nextStation.setText("");
			nextStationName = "";
			Helper.showSoundToast(this, getString(R.string.undefined), false);
		}
	}

	/**
	 * 扫描码判断
	 * 
	 * @param code
	 *            扫描码
	 * @return true/ok or false
	 */
	private boolean CheckScanCode(String code) {
		boolean ret = false;
		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code, EnumTableNames.STATUS_TABLE_SEND_CAR);

		switch (status) {
		// 条码空
		case CODE_EMPTY:
			// Helper.showSoundToast(
			// this,
			// getString(R.string.code_empty), false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(this, getString(R.string.error_code), false);
			break;
		// 非法条码
		case CAR_SEAL_ILLEGAL:
			Helper.showSoundToast(this, "非法铅封条码", false);
			break;
		case CODE_SEAL_OK:

			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	/**
	 * 检查数据是否合法
	 * 
	 * @return boolean
	 */
	@SuppressLint("NewApi")
	private boolean CheckItemData(String barcode, int handleType) {
		boolean ret = false;
		if (handleType == HAND_RESULT) {

			if (ScanRuleManager.getInstance(this).isCarSealCode(barcode)) {
				;
			} else {
				Helper.showSoundToast(this, "非申通铅封条码!", false);
				code.setText("");
				code.requestFocus();
				return ret;
			}
			// 检查铅封号
			if (!CheckScanCode(barcode)) {
				code.setText("");
				code.requestFocus();
				return ret;
			}
		}
		if (nextStation.getText().toString().length() == 0) {
			Helper.showSoundToast(this, "下一站不能为空!", false);
			nextStation.requestFocus();
			return ret;
		}
		if (!nextStationName.equals(nextStation.getText().toString())) {
			Helper.showSoundToast(this, "请选择正确的下一站!", false);
			nextStation.requestFocus();
			nextStation.setText("");
			return ret;
		}
		if (nextStationCode.isEmpty()) {
			Helper.showSoundToast(this, "下一站不能为空!", false);
			nextStation.requestFocus();
			return ret;
		}
		if (carCode.getText().toString().length() != CARID_LENGTH) {
			Helper.showSoundToast(StoScanSendCarScanActivity.this, "车辆id位数不对",
					false);
			carCode.setText("");
			carCode.requestFocus();
			return ret;
		}
		if (!carCode.getText().toString().matches("[0-9]+")) {
			Helper.showSoundToast(StoScanSendCarScanActivity.this, "车辆id非法",
					false);
			carCode.setText("");
			carCode.requestFocus();
			return ret;
		}

		return true;
	}

	@Override
	public void onBackPressed() {
		// 确定退出吗?
		showNotice();
		// super.onBackPressed();

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		edit.clear();
		edit = null;
		handler.removeMessages(HAND_RESULT);
		super.onDestroy();
	}

	@Override
	protected void handlerScanData(String scanData) {

		if (scanData != null && !scanData.equals("")) {
			String result = scanData.toString();
			// 下一站编号
			if (result.length() == CARID_LENGTH) {
				nextStation.setText(result);
				selectNextStation();
			} else {
				code.setText(result);
				code.setSelection(code.length());

				if (CheckScanCode(result)) {
					if (CheckItemData(result, 0)) {
						processScanData();
						code.setText("");
						code.requestFocus();
					}
				}
				code.setText("");

			}
		} else {

			// Helper.showSoundToast(StoScanSendCarScanActivity.this,
			// "条码不能为空", false);
		}

	}

}
